package com.xin.springcloudquartz.bean;

import com.xin.springcloudquartz.config.ProjectUrlConfig;
import com.xin.springcloudquartz.dataobject.Event;
import com.xin.springcloudquartz.enums.EventStatusEnum;
import com.xin.springcloudquartz.service.EventService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
public class MyBean implements Job {

    public static EventService eventService;

    private RestTemplate restTemplate=new RestTemplate();



    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String event = jobDataMap.getString("eventId");
        String date = jobDataMap.getString("date");
        //查询事件
        if (ObjectUtils.isEmpty(eventService)) {
            log.info("eventService为null");
        }
        Event one = eventService.findOne(event);

        if (ObjectUtils.isEmpty(one)) {
            log.info("事件不存在");
        }
        if (one.getStatus() == 1) {
            log.info("事件已执行!");
        }
        if (one.getStatus()==0){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        SmsUtils.sendSms();
            one.setStatus(EventStatusEnum.STOP.getCode());
            Event update = eventService.update(one);
            if (!ObjectUtils.isEmpty(update)) {
                log.info("当前时间:" + simpleDateFormat.format(new Date()));
                String url = "http://xinlovezhang.top".concat("/push/quartz").concat("?openId=").concat(update.getOpenId()).concat("&date=").concat(update.getTime()).concat("&message=").concat(update.getContent());
                boolean flag = restTemplate.getForObject(url, Boolean.class);
                if (flag) {
                    log.info("消息发送成功!");
                }
            }
        }
    }


    public void message() throws JobExecutionException {

    }
}
